package com.ygqh.baby.excel;

import com.ygqh.baby.excel.domain.AbstractExcelReadEntity;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.List;

/**
 * Excel 工具类 支持 xls，xlsx的读入
 * 1.读取Excel  需创建一个 ExcelReadEntity 并继承 AbstractExcelReadEntity
 * 针对必传项使用 ExcelField 注解 设置 head 属性（Excel中文列头信息 例：订单编号）， required 属性默认为true，
 * 读取时会校验是否为空，并将错误信息写入 AbstractExcelReadEntity 的errorMsg 中
 *
 * @author guohao
 */
public class ExcelHandler {

    public static <T extends AbstractExcelReadEntity> List<T> loadExcel(MultipartFile multipartFile, Class<T> classzz) {
        if (multipartFile == null) {
            return null;
        }
        try {
            InputStream is = multipartFile.getInputStream();
            Workbook workbook = WorkbookFactory.create(is);
            return readExcel(workbook, classzz);

        } catch (Exception e) {
            throw new RuntimeException("importExcel fail ," + e.getMessage());
        }

    }

    public static <T extends AbstractExcelReadEntity> List<T> readExcel(Workbook workbook, Class<T> classzz) {
        return ExcelReadHandler.readExcel(workbook, classzz);
    }

}